package com.liy.cloud.base.rest;

import com.liy.cloud.base.entity.BaseEquTypeParamEntity;
import com.das.framework.common.annotation.MethodPermission;
import com.das.framework.common.constants.PermissionCodes;
import com.das.framework.common.extvo.ResultVO;
import com.das.framework.common.office.ExportExcel;
import com.das.framework.common.office.ReadExcel;
import com.das.framework.common.vo.PageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.das.framework.common.annotation.ActionPermission;

import com.liy.cloud.base.service.BaseEquTypeParamService;
import com.das.framework.common.web.controller.BaseCrudController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.DecimalFormat;
import java.util.*;

/**
 * 关联设备的种类和参数信息 服务
 * @ClassName: BaseEquTypeParamRest
 * @Description: 
 * @author zhangw
 * @date 2018-07-01 18:00:01
 */
@RestController
@RequestMapping("/equtype/param")
@ActionPermission(code="BASE.BASEEQUTYPEPARAM", description="设备种类参数管理")
public class BaseEquTypeParamRest extends BaseCrudController<BaseEquTypeParamService, BaseEquTypeParamEntity>{

    @Resource
    private BaseEquTypeParamService baseEquTypeParamService;

    /*
     * 导出设备种类参数模板文件名称
     */
    @Value("${dascloud.template.reportEquypeParamExcel}")
    private String reportEquypeParamExcel;



    @RequestMapping(value = {"/save"}, method = {RequestMethod.POST})
    @ResponseBody
    @MethodPermission(codes = {"INSERT"}, description = "新增")
    public ResultVO save(@RequestBody Map<String, Object> params) {
        try {
            List<BaseEquTypeParamEntity> typeParamList = (List<BaseEquTypeParamEntity>) params.get("typeParamList");
            String typeId = (String) params.get("typeId");
            baseEquTypeParamService.save(typeParamList, typeId);
            return new ResultVO(true, "保存成功", "200");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return new ResultVO(false, "新增时发生错误:" + var4.getMessage(), "500");
        }
    }

    @RequestMapping(value = {"/update"}, method = {RequestMethod.POST})
    @ResponseBody
    @MethodPermission(codes = {"UPDATE"}, description = "修改")
    public ResultVO update(@RequestBody List<BaseEquTypeParamEntity> typeParamList) {
        try {
            if(typeParamList.size() == 0){
                return new ResultVO(false, "没有存在选择的参数，请选择！", "500");
            }
            baseEquTypeParamService.update(typeParamList);
            return new ResultVO(true, "保存成功", "200");
        } catch (Exception var4) {
            log.error(var4.getMessage(), var4);
            return new ResultVO(false, "新增时发生错误:" + var4.getMessage(), "500");
        }
    }


    /**
     * 查询种类参数明细信息
     *
     * @param 
     * @return 
     * @auther libs
     * @date 2018/10/25 17:56
     */
    @ResponseBody
    @RequestMapping(value = {"get/type/param/info"}, method = {RequestMethod.GET, RequestMethod.POST})
    @MethodPermission(codes = PermissionCodes.SEARCH, description = "查询种类参数明细信息")
    public ResultVO getTypeParamInfo() {
        ResultVO resultVO = new ResultVO();
        try{
            resultVO.setData(baseEquTypeParamService.getTypeParamInfo());
        }catch (Exception e){
            log.error("查询种类参数明细信息时出错：", e);
            resultVO.setSuccess(false);
            resultVO.setMessage("查询种类参数明细信息时出错：" + e.getMessage());
        }
        return resultVO;
    }


    /**
     * 查询种类下的所有参数分组名
     *
     * @param params
     * @return
     * @auther zhangw
     * @date 2018/11/01 17:56
     */
    @ResponseBody
    @RequestMapping(value = {"get/typeid/groupname"}, method = {RequestMethod.POST})
    public ResultVO getVersion(@RequestBody Map<String, String> params) {
        ResultVO resultVO = new ResultVO();
        try{
            String typeId = params.get("typeId");
            List<String> groupnameList = baseEquTypeParamService.selectTypeGroupname(typeId);
            resultVO.setData(groupnameList);
        }catch (Exception e){
            log.error("生成参数版本时出错：", e);
            resultVO.setSuccess(false);
            resultVO.setMessage("生成参数版本时出错：" + e.getMessage());
        }
        return resultVO;
    }


    /**
     * @Author: zhangw
     * @Date: 2018/11/07  9:47
     * @Description: 导入设备种类参数文件
     **/
    @RequestMapping("/upload")
    @MethodPermission(codes = PermissionCodes.UPDATE, description = "导入设备种类参数")
    public ResultVO uploadFile(@RequestParam("file") MultipartFile file) {
        ResultVO resultVO = new ResultVO();

        try {
            if (file == null) {
                resultVO.setSuccess(false);
                resultVO.setMessage("导入设备种类参数文件异常无法解析,设备种类参数导入失败!");
                return resultVO;
            }

            String fileName = file.getOriginalFilename();
            // 文件名不合法
            if (!(fileName.endsWith("xls") || fileName.endsWith("xlsx"))) {
                return new ResultVO(false, "导入设备种类参数文件格式不合法,设备种类参数导入失败! 请导入.xls或.xlsx后缀文件", "500");
            }
            List<Map<Integer, Object>> list = null;
            if(file.getOriginalFilename().endsWith("xls")){
                list = ReadExcel.readExcel(file.getInputStream(), false);
            }else if(file.getOriginalFilename().endsWith("xlsx")){
                list = ReadExcel.readExcel(file.getInputStream(), true);
            }

            if (list.size() > 1) {
                List<BaseEquTypeParamEntity> equTypeParamList = new ArrayList();
                Iterator<Map<Integer, Object>> it = list.iterator();
                it.next();// 过滤第一行的标题
                while (it.hasNext()) {
                    BaseEquTypeParamEntity equtTypeParam = new BaseEquTypeParamEntity();
                    Map<Integer, Object> item = it.next();
                    DecimalFormat df = new DecimalFormat("0");
                    if(item.get(0) != null){
                        equtTypeParam.setTypeId(df.format(item.get(0)));
                    }
                    if(item.get(1) != null){
                        equtTypeParam.setParamId(df.format(item.get(2)));
                    }
                    if(item.get(2) != null){
                        equtTypeParam.setParamValue(df.format(item.get(4)));
                    }
                    equTypeParamList.add(equtTypeParam);
                }
                // 开启事务保存数据
                baseEquTypeParamService.save(equTypeParamList, equTypeParamList.get(0).getTypeId());
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new ResultVO(false, "设备种类参数导入失败:" + e.getMessage(), "500");
        }
        return resultVO;
    }


    /**
     * @Author: zhangw
     * @Date: 2018/11/07  9:47
     * @Description: 导出设备种类参数文件
     **/
    @RequestMapping("/export/{typeId}")
    @MethodPermission(codes = PermissionCodes.UPDATE, description = "导出设备种类参数")
    public ResultVO exportFile(@PathVariable(value = "typeId") String typeId){
        ResultVO resultVO = new ResultVO();

        try {
            Map<String, Object> map = new HashMap();
            PageVO page = new PageVO(1, 1000);
            BaseEquTypeParamEntity entity = new BaseEquTypeParamEntity();
            entity.setTypeId(typeId);
            List<BaseEquTypeParamEntity> equTypeParamList = baseEquTypeParamService.selectByTypeIdExport(entity);
            map.put("list", equTypeParamList);

            // 系统临时目录
            String systemTempDir = System.getProperty("java.io.tmpdir");
            // 模板目录
            String templateDir = this.getClass().getClassLoader().getResource("template").getFile();
            String decodeTemplateDir = java.net.URLDecoder.decode(templateDir, "utf-8");
            ExportExcel excel = new ExportExcel();
            // 模板绝对路径
            String templatePathFile = decodeTemplateDir + File.separator + reportEquypeParamExcel;
            // 模板填充完成后文件名称
            String destFileName = "reportEquypeParamExcel_" + System.currentTimeMillis() + ".xlsx";
            // 模板填充完成文件
            String destPathFile = systemTempDir + File.separator + destFileName;
            // 导出 excel
            excel.export(templatePathFile, map, destPathFile);


            File desFile = new File(destPathFile);
            // 取得文件名。
            String filename = desFile.getName();
            // 以流的形式下载文件。
            InputStream fis = new BufferedInputStream(new FileInputStream(
                    destPathFile));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();
            // 清空response
            response.reset();
            response.addHeader("Content-Disposition", "attachment;filename="+ new String(filename.getBytes()));
            OutputStream os= new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/vnd.ms-excel;charset=UTF-8");
            os.write(buffer);
            os.flush();
            os.close();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return new ResultVO(false, "设备种类参数导出失败:" + e.getMessage(), "500");
        }
        return resultVO;
    }

}